<template>
	<view>
		正在登录
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isWeixin: false,
			}
		},
		onLoad(options) {
	
			this.wxLogin()
		},
		methods: {
			wxLogin() {
				let that = this;
				let code = this.getUrlCode('code');
				let accessToken = this.$storage.getStorageSync(this.$const.USER_TOKEN_KEY);
				console.log('get----?code-->', code, accessToken)
				
				if(!accessToken){
					if (code) {
						uni.showLoading({
							mask: true,
							title: '正在登录',
						});
						this.$request({
							url: that.$api.app.wxLogin,
							method: 'get',
							data: {
								code: code
							},
						}).then(info => {
							console.log(info);
							uni.hideLoading();
							if (info.code == 1) {
								that.$storage.setStorageSync(that.$const.USER_TOKEN_KEY, info.data.token);
								that.backRedirect();
							} else {
								uni.showToast({
									title: '登录失败',
								});
							}
					
						}).catch(error => {
							uni.hideLoading();
							console.log(error)
						})
					}else{
						this.getWeChatCode()
					}
				}else{
					that.backRedirect();
				}
				
	
			

			},
			backRedirect(){
				let redirect_url = this.$storage.getStorageSync(this.$const.REDIRECT_URL);
				if(redirect_url){
					this.$storage.setStorageSync(this.$const.REDIRECT_URL,null);
					window.location.href = redirect_url;
				}else{
					uni.redirectTo({
					    url: '/pages/luckyDraw/luckyDraw'
					});
				}
			},
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1]
					.replace(/\+/g, '%20')) || null
			},
			getWeChatCode() {
				let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址
				let appid = uni.getStorageSync("appInfo").appid

				//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid +
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
			}

		}
	}
</script>

<style>

</style>
